package springapp.service;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import springapp.dao.IndustryDao;
import springapp.entity.IndustryEntity;
import springapp.jaxb.IndustriesConfig;
import springapp.jaxb.Industry;
import springapp.util.Utils;

@Service
public class IndustryService implements IServiceConstants, IIndustryService {

	@Autowired(required = true)
	private CacheService cacheService;

	@Autowired(required = true)
	private IndustryDao industryDao;

	@Autowired(required = true)
	private ResourceService resourceService;

	private ICache<Integer, String> industryCache;

	@SuppressWarnings("unchecked")
	@PostConstruct
	public void initialise() throws IOException {

		IndustriesConfig config;
		try {
			Resource resource = resourceService
					.getResource("classpath:xml/industry.xml");
			config = Utils.getConfig(resource.getInputStream(),
					new IndustriesConfig());
			industryDao.setInitialized();
			List<IndustryEntity> allEntities = getAllEntities();
			List<Industry> industry2 = config.getIndustries();
			Utils.removeOldElements(industry2, allEntities);

			IndustryEntity[] entitiesToSave = new IndustryEntity[industry2
					.size()];
			int counter = 0;
			for (Industry industry : industry2) {
				entitiesToSave[counter++] = new IndustryEntity(
						industry.getName());
			}

			industryDao.saveEntities(entitiesToSave);

			Collections.addAll(allEntities, entitiesToSave);

			this.cacheService.addToCache(allEntities, INDUSTRY);

			industryCache = (ICache<Integer, String>) cacheService
					.getCache(INDUSTRY);
			industryDao.unset();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

	@Transactional(readOnly = true)
	public List<IndustryEntity> getAllEntities() {
		List<IndustryEntity> allEntities = industryDao.getAllEntities();
		return allEntities;
	}

	public Integer getIndustryId(String industry) {
		return industryCache.getKeyForValue(industry);
	}

	public Set<String> getAllIndustries() {
		return industryCache.getValues();
	}

	public String getIndustryName(Integer industryId) {
		return industryCache.getValueForKey(industryId);
	}

}
